package com.jbit.config.security.component;

import com.jbit.pojo.Menu;
import com.jbit.pojo.Role;
import com.jbit.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求URL 分析请求所需的角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService iMenuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        System.out.println("===========>CustomFilter");
        //获取请求的url
        String url = ((FilterInvocation) o).getRequestUrl();
        System.out.println("请求的URL=============>" + url);
        List<Menu> menus = iMenuService.getMenuWithRoles();

        for (Menu menu : menus) {
            //判断请求的url跟菜单里的url是否相同
            if (antPathMatcher.match(menu.getUrl(), url)) {
                //如果匹配上了，就把当前URL所需要的角色名字设置到 ConfigAttribute里
                String[] strings = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(strings);
            }
        }
        //如果匹配不上 默认登录的角色
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
